"""
AIPPT PPT Generation Service
Handles PPT generation workflow (V2 API - Recommended)
"""
from typing import Dict, Any, Optional, List
from src.llm.aippt_app.utils.api_client import AIPPTAPIClient


class PPTGenerationService:
    """Service for PPT generation using V2 API"""

    def __init__(self, client: Optional[AIPPTAPIClient] = None):
        """
        Initialize PPT generation service

        Args:
            client: AIPPTAPIClient instance, creates new if not provided
        """
        self.client = client or AIPPTAPIClient()

    def get_generation_options(self, lang: str = 'zh') -> Dict[str, Any]:
        """
        Get available generation options

        Args:
            lang: Language code

        Returns:
            Generation options (audience, lang, pageCount, style, etc.)
        """
        try:
            response = self.client.get_generation_options(lang)
            if response.get('code') == 0 or response.get('data'):
                return response
            else:
                raise Exception(f"Failed to get generation options: {response.get('message')}")
        except Exception as e:
            print(f"Error getting generation options: {str(e)}")
            raise

    def create_task_from_text(
        self,
        content: str = None,
        task_type: int = 1,
        files: Optional[list] = None
    ) -> str:
        """
        Create a task from text content or files

        Args:
            content: Text content (theme, requirements, etc.) - optional for file-based types
            task_type: Task type (1=smart generation, 2=upload file, 3=mind map, 4=word to ppt, 5=web link, 6=paste text, 7=markdown)
            files: List of file tuples for upload (required for types 2, 3, 4)

        Returns:
            Task ID
        """
        try:
            response = self.client.create_task(task_type, content, files)
            if response.get('code') == 0 and response.get('data'):
                # API returns 'id' field
                task_id = response['data'].get('id') or response['data'].get('taskId')
                if task_id:
                    return task_id
                else:
                    raise Exception("Task ID not found in response")
            else:
                raise Exception(f"Failed to create task: {response.get('message')}")
        except Exception as e:
            print(f"Error creating task: {str(e)}")
            raise

    def generate_ppt_content(
        self,
        task_id: str,
        prompt: Optional[str] = None,
        template_id: Optional[str] = None,
        audience: Optional[str] = None,
        lang: str = 'zh',
        page_count: int = 10
    ) -> Dict[str, Any]:
        """
        Generate PPT outline and content

        Args:
            task_id: Task ID from create_task
            prompt: Additional generation prompt
            template_id: Template ID to use
            audience: Target audience
            lang: Language
            page_count: Number of pages

        Returns:
            Generated content with markdown outline
        """
        try:
            response = self.client.generate_content(
                task_id=task_id,
                is_stream=False,
                prompt=prompt,
                template_id=template_id,
                audience=audience,
                lang=lang,
                pageCount=page_count
            )
            return response
        except Exception as e:
            print(f"Error generating content: {str(e)}")
            raise

    def modify_content(
        self,
        task_id: str,
        instruction: str
    ) -> Dict[str, Any]:
        """
        Modify existing content based on user instruction

        Args:
            task_id: Task ID
            instruction: User instruction for modification

        Returns:
            Modified content
        """
        try:
            response = self.client.update_content(
                task_id=task_id,
                question=instruction,
                is_stream=False
            )
            return response
        except Exception as e:
            print(f"Error modifying content: {str(e)}")
            raise

    def generate_ppt_file(
        self,
        task_id: str,
        markdown: str,
        template_id: str
    ) -> Dict[str, Any]:
        """
        Generate final PPT file from markdown content

        Args:
            task_id: Task ID
            markdown: Markdown outline and content
            template_id: Template ID to use

        Returns:
            PPT file information with download URL
        """
        try:
            response = self.client.generate_pptx(
                task_id=task_id,
                markdown=markdown,
                template_id=template_id
            )
            return response
        except Exception as e:
            print(f"Error generating PPT file: {str(e)}")
            raise

    def create_ppt_from_text(
        self,
        content: str,
        template_id: str,
        prompt: Optional[str] = None,
        page_count: int = 10,
        lang: str = 'zh'
    ) -> Dict[str, Any]:
        """
        Complete workflow: Create task, generate content, and generate PPT

        Args:
            content: Input text content
            template_id: Template ID to use
            prompt: Additional generation prompt
            page_count: Number of pages
            lang: Language

        Returns:
            Final PPT information with all intermediate results
        """
        result = {
            'task_id': None,
            'content': None,
            'ppt': None
        }

        try:
            # Step 1: Create task
            print("Step 1: Creating task...")
            task_id = self.create_task_from_text(content)
            result['task_id'] = task_id
            print(f"Task created with ID: {task_id}")

            # Step 2: Generate content
            print("Step 2: Generating content...")
            content_response = self.generate_ppt_content(
                task_id=task_id,
                prompt=prompt,
                template_id=template_id,
                page_count=page_count,
                lang=lang
            )
            result['content'] = content_response
            print("Content generated successfully")

            # Extract markdown from content response
            markdown = None
            if content_response.get('data'):
                markdown = content_response['data'].get('markdown')

            if not markdown:
                raise Exception("Failed to extract markdown from content response")

            # Step 3: Generate PPT file
            print("Step 3: Generating PPT file...")
            ppt_response = self.generate_ppt_file(
                task_id=task_id,
                markdown=markdown,
                template_id=template_id
            )
            result['ppt'] = ppt_response
            print("PPT file generated successfully")

            return result

        except Exception as e:
            print(f"Error in PPT creation workflow: {str(e)}")
            result['error'] = str(e)
            return result
